﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MyCoreLib.Automation.Data.SqlClient.Metadata;

namespace MyCoreLib.Automation.Data.SqlClient.Model
{
    class DbSchemaInfo
    {
        private readonly Lazy<HashSet<string>> StoredProcedureFullNames;

        public DbSchemaInfo(ISqlSchemaReader schemaReader, CancellationToken token)
        {
            var spFullNamesTask = BuildSpFullNamesLookupAsync(schemaReader, token);

            StoredProcedureFullNames = new Lazy<HashSet<string>>(() => spFullNamesTask.Result);
        }

        public bool ProcedureExist(StoredProcedureSelectorInfo procedure)
        {
            if (ReferenceEquals(procedure, null)) { return false; }
            return StoredProcedureFullNames.Value.Contains(procedure.FullName);
        }

        private async Task<HashSet<string>> BuildSpFullNamesLookupAsync(ISqlSchemaReader schemaReader, CancellationToken token)
        {
            var fullNames = await schemaReader.LoadStoredProcedureFullNamesAsync(token);
            return new HashSet<string>(fullNames, StringComparer.OrdinalIgnoreCase);
        }
    }
}
